const adjustMatchJson = require("../algorithm/adjustMatchAlgo.json")
type Gender = "male" | "female";

interface AdjustData {
  gender: Gender;
  age: number;
  height: number; // 单位：cm
  weight: number; // 单位：kg
}

// H5本地算法服务
export default class AlgorithmService {
    // 判断某个数值是否在一个形如 "12-25" 的区间字符串中
    isInRange(value: number, rangeStr: string): boolean {
        const [min, max] = rangeStr.split('-').map(parseFloat);
        return value >= min && value <= max;
    }
    /**
     * 匹配最合适的数组结果
     */
    adjustMatch(data: AdjustData): number[] | null {

         // 参数判空
        if (data == null) {
            console.warn("adjustMatch: 参数为空");
            return null;
        }

        const { gender, age, height, weight } = data;

        // 进一步检查各个字段是否有效
        if (typeof gender !== "string" || (gender !== "male" && gender !== "female")) {
            console.warn("adjustMatch: gender 参数不合法");
            return null;
        }

        if (typeof age !== "number" || isNaN(age) || age <= 0) {
            console.warn("adjustMatch: age 参数不合法");
            return null;
        }

        if (typeof height !== "number" || isNaN(height) || height <= 0) {
            console.warn("adjustMatch: height 参数不合法");
            return null;
        }

        if (typeof weight !== "number" || isNaN(weight) || weight <= 0) {
            console.warn("adjustMatch: weight 参数不合法");
            return null;
        }

        const bmi = weight / Math.pow(height / 100, 2); // cm 转为 m

        const genderData = adjustMatchJson[gender];
        if (!genderData) return null;

        // 找到匹配的年龄段
        const ageRange = Object.keys(genderData).find(range => this.isInRange(age, range));
        if (!ageRange) return null;

        const heightData = genderData[ageRange];
        const heightRange = Object.keys(heightData).find(range => this.isInRange(height, range));
        if (!heightRange) return null;

        const bmiData = heightData[heightRange];
        const bmiRange = Object.keys(bmiData).find(range => this.isInRange(bmi, range));
        if (!bmiRange) return null;

        return bmiData[bmiRange];
    }

}